package main

import (
	"fmt"
	log "github.com/golang/glog"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	pb "grpc-test/pb"
	"time"
)

type server struct{}

func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
	return &pb.HelloReply{Message: "Hello " + in.Name, Xx: &pb.HelloReply_XX{A: []string{"1", "2"}}}, nil
}

func (s *server) Add(ctx context.Context, in *pb.AddRequest) (*pb.AddReply, error) {
	if in.B == 0 {
		return nil, grpc.Errorf(codes.InvalidArgument, "no zero")
	}
	c := in.A / in.B
	log.Info("Add", in.A, in.B, c)
	return &pb.AddReply{C: c}, nil
}

func (s *server) StreamHello(in *pb.StreamHelloRequest, out pb.Greeter_StreamHelloServer) error {
	log.Infof("StreamHello %+v", in)
	for i := in.Start; i < in.End; i += in.Step {
		body := fmt.Sprintf("send %d", i)
		log.Error("send", body)
		err := out.Send(&pb.StreamHelloReply{Body: body})
		if err != nil {
			log.Info("send", err)
		}
		time.Sleep(time.Second)
	}
	log.Info("end")
	return nil
}

func (s *server) StreamHello2(in *pb.StreamHello2Request, out pb.Greeter_StreamHello2Server) error {
	log.Infof("StreamHello %+v", in)
	for i := 1; i < 10; i++ {
		body := fmt.Sprintf("send %d", i)
		log.Error("send", body)
		err := out.Send(&pb.StreamHelloReply{Body: body})
		if err != nil {
			log.Info("send", err)
		}
		time.Sleep(time.Second)
	}
	log.Info("end")
	return nil
}
